package com.jastar.android.game.go;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.jastar.android.test.R;

import java.text.MessageFormat;

public class GameActivity extends AppCompatActivity {
    public static final String SIGN_IS_AI = "IS_AI";

    private GoBoardView goBoard;
    private TextView tvStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_go_game);

        goBoard = findViewById(R.id.go_board);
        tvStatus = findViewById(R.id.tv_status);

        updateStatus();

        boolean isAI = getIntent().getBooleanExtra(SIGN_IS_AI, false);
        if (isAI) goBoard.addAIPlayer();

        goBoard.setFocusable(true);
        goBoard.requestFocus();
        goBoard.setTouchListener((player, extra) -> updateStatus());
        goBoard.setOnGameEndListener((winner, extra) -> {
            int[] scores = (int[]) extra;
            String msg = MessageFormat.format("黑方{0}目，白方{1}目，{2}方胜利!", scores[0], scores[1], (winner == 1) ? "黑" : "白");
            if (scores[0] == scores[1]) {
                msg = MessageFormat.format("黑方{0}目，白方{1}目，和棋!", scores[0], scores[1]);
            }
            tvStatus.setTextColor(0xFFAAAAAA);
            tvStatus.setText(msg);
            int idx = msg.indexOf("胜利");
            if (idx > 1) {
                changeColor(tvStatus, winner == 1 ? Color.BLACK : Color.WHITE, idx - 2, idx);
            }
        });

        findViewById(R.id.btn_undo).setOnClickListener(v -> goBoard.undoMove());
        findViewById(R.id.btn_end_game).setOnClickListener(v -> goBoard.calculateWinner());
    }

    private void updateStatus() {
        String text = "当前玩家：" + (goBoard.getCurrentPlayer() == 1 ? "黑方" : "白方");
        tvStatus.setTextColor(goBoard.getCurrentPlayer() == 1 ? Color.BLACK : Color.WHITE);
        tvStatus.setText(text);
    }

    private void changeColor(TextView textView, int color, int start, int end) {
        SpannableString spannableString = new SpannableString(textView.getText());
        spannableString.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvStatus.setText(spannableString);
    }

}